﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using NCommonLib.Extensions;

namespace NPortableEngine
{
    internal class HttpEngine
    {
        //HttpCore
        //TODO 应该加上状态监控以及超时处理
        internal async Task<WebResponse> Request(string url,Dictionary<string,object> headers,Dictionary<string,object> parameters,HttpMethodType method,ReqType reqType)
        {
            HttpWebRequest requestor = null;

            try
            {
                string paramStr = parameters.ToStringParams();

                if (method == HttpMethodType.GET)
                {
                    if (reqType == ReqType.IMAGE)
                    {
                        requestor = WebRequest.Create(url) as HttpWebRequest;
                    }
                    else
                    {
                        requestor = WebRequest.Create(url + "?" + paramStr) as HttpWebRequest;
                    }
                    requestor.Method = "GET";
                }
                else if (method == HttpMethodType.POST)
                {
                    requestor = (HttpWebRequest)WebRequest.Create(url);
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, object> item in headers)
                        {
                            requestor.Headers[item.Key] = (string)item.Value;
                        }
                    }
                    requestor.Method = "POST";
                    requestor.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

                    using (Stream stream = await requestor.GetRequestStreamAsync().ConfigureAwait(false))
                    {
                        byte[] content = Encoding.UTF8.GetBytes(paramStr);
                        stream.Write(content, 0, content.Length);
                    }
                }
                //Time out control
                Task<WebResponse> httpTask = requestor.GetResponseAsync();
                var completeTask = await Task.WhenAny(httpTask, Task.Delay(5000));

                if (completeTask == httpTask)
                {
                    return await httpTask.ConfigureAwait(false);
                }
                else
                {
                    //in this place is should define a custom exception type ,so it can tell the ui how to show the error msg;
                    throw new Exception("TimeOut");
                }
                //return await requestor.GetResponseAsync().ConfigureAwait(false);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }
}
